<template>
    <div class="contract-form">
        <!-- 基本信息 -->
        <h3>基本信息</h3>
        <el-form :model="form" :rules="rules" ref="contractForm" label-width="120px" class="basic-info">
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="所属小区" prop="communityId">
                        <el-select v-model="form.communityId" placeholder="请选择小区" style="width: 100%;"
                            @change="handleCommunityChange" clearable>
                            <el-option v-for="item in communityOptions" :key="item.id" :label="item.communityName"
                                :value="item.communityId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="广告位" prop="advertisingId">
                        <el-select v-model="form.advertisingId" placeholder="请选择广告位" style="width: 100%;"
                            @change="handleAdvertisingChange" clearable :disabled="!form.communityId">
                            <el-option v-for="item in advertisingOptions" :key="item.advertisingId"
                                :label="item.advertisingName" :value="item.advertisingId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="广告位价格">
                        <el-input v-model="feeAmount" disabled style="width: 100%;" />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="租赁方" prop="leaseCompany">
                        <el-input v-model="form.leaseCompany" placeholder="请输入租赁方" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="联系人" prop="leaseName">
                        <el-input v-model="form.leaseName" placeholder="请输入租赁方联系人" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="联系电话" prop="leasePhone">
                        <el-input v-model="form.leasePhone" placeholder="请输入租赁方联系人电话" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="广告位位置">
                        <el-input v-model="form.advertisingPosition" disabled style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="广告位大小">
                        <el-input v-model="form.advertisingSize" disabled style="width: 90%;" /><label
                            style="margin-left: 10px;">m²</label>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <!-- 合同信息 -->
        <h3>合同信息</h3>
        <el-form :model="form" :rules="rules" ref="contractForm" label-width="120px" class="contract-info">
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="合同编号" prop="contractNumber">
                        <el-input v-model="form.contractNumber" placeholder="请输入合同编号" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="承租方" prop="tenantName">
                        <el-input v-model="form.tenantName" placeholder="请输入承租方" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="签订日期" prop="signingDate">
                        <el-date-picker v-model="form.signingDate" type="date" placeholder="请选择签订日期"
                            style="width: 100%;" />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="法定代表" prop="legalRepresentative">
                        <el-input v-model="form.legalRepresentative" placeholder="请输入法定代表" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="承租方电话" prop="tenantPhone">
                        <el-input v-model="form.tenantPhone" placeholder="请输入承租方电话" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="租期(月)" prop="leaseTerm">
                        <el-input v-model.number="form.leaseTerm" placeholder="自动计算" style="width: 100%;" disabled />
                    </el-form-item>
                </el-col>


                <el-col :span="8">
                    <el-form-item label="起租日期" prop="startDate">
                        <el-date-picker v-model="form.startDate" type="date" placeholder="请选择起租日期"
                            style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="结束日期" prop="stopDate">
                        <el-date-picker v-model="form.stopDate" type="date" placeholder="请选择结束日期"
                            style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="收费面积">
                        <el-input v-model="form.collectionArea" disabled style="width: 90%;" /><label
                            style="margin-left: 10px;">m²</label>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="押金">
                        <el-input v-model="brokerage" disabled style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="租金方式" prop="depositId">
                        <el-select v-model="form.depositId" placeholder="请选择租金方式" @change="handleRentWayChange"
                            style="width: 100%;">
                            <el-option v-for="item in depositOptions" :key="item.depositId" :label="item.depositName"
                                :value="item.depositId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="合同总额">
                        <el-input v-model="TotalAmount" disabled style="width: 100%;" />
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="押金说明" prop="depositDescription">
                        <el-input v-model="form.depositDescription" placeholder="请输入押金说明" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="备注" prop="remarks">
                        <el-input v-model="form.remarks" placeholder="请输入备注" style="width: 100%;" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <!-- 操作按钮 -->
        <div class="button-group" style="text-align: right;margin-right: 30px;">
            <el-button type="primary" @click="handleSave" :loading="loading">提交</el-button>
            <el-button @click="goBack">取消</el-button>
        </div>

        <!-- 支付状态对话框 -->
        <el-dialog title="支付处理中" :visible.sync="showPaymentDialog" width="30%" :close-on-click-modal="false"
            :show-close="false">
            <div>
                <el-progress :percentage="(pollingCount / maxPollingCount) * 100"
                    :status="pollingCount >= maxPollingCount ? 'exception' : 'success'">
                </el-progress>
                <p style="text-align: center; margin-top: 20px;">
                    {{ pollingCount >= maxPollingCount ? '支付状态检查超时' : '正在等待支付结果...' }}
                </p>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import request, { communityRequest } from '@/utils/request';

export default {
    name: 'AddAdvertisingLease',
    data() {
        // 自定义验证规则
        const validatePhone = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请输入联系电话'));
            }
            if (!/^1[3-9]\d{9}$/.test(value)) {
                return callback(new Error('请输入正确的手机号码'));
            }
            callback();
        };

        const validateDate = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请选择日期'));
            }
            callback();
        };

        return {
            feeAmount: 0,
            brokerage: 0,
            TotalAmount: 0,
            loading: false,
            form: {
                communityId: "",
                advertisingId: "",
                depositId: 1,
                contractNumber: "",
                leaseCompany: "",
                leaseName: "",
                leasePhone: "",
                tenantName: "",
                tenantPhone: "",
                legalRepresentative: "",
                collectionArea: "",
                signingDate: "",
                leaseTerm: 1,
                startDate: "",
                stopDate: "",
                depositDescription: "",
                remarks: "",
                advertisingPosition: "",
                advertisingSize: ""
            },
            communityOptions: [],
            advertisingOptions: [],
            depositOptions: [],
            rules: {
                communityId: [{ required: true, message: '请选择小区', trigger: 'change' }],
                advertisingId: [{ required: true, message: '请选择广告位', trigger: 'change' }],
                leaseCompany: [{ required: true, message: '请输入租赁方', trigger: 'blur' }],
                leaseName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
                leasePhone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
                contractNumber: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
                tenantName: [{ required: true, message: '请输入承租方', trigger: 'blur' }],
                signingDate: [{ required: true, validator: validateDate, trigger: 'change' }],
                legalRepresentative: [{ required: true, message: '请输入法定代表', trigger: 'blur' }],
                tenantPhone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
                leaseTerm: [
                    { required: true, message: '请输入租期', trigger: 'blur' },
                    { type: 'number', message: '租期必须为数字', trigger: 'blur' }
                ],
                startDate: [{ required: true, validator: validateDate, trigger: 'change' }],
                stopDate: [{ required: true, validator: validateDate, trigger: 'change' }],
                depositId: [{ required: true, message: '请选择租金方式', trigger: 'change' }],
            },
            pollingCount: 0,      // 当前轮询次数
            maxPollingCount: 15,  // 最大轮询次数（30秒/2秒=15次）
            showPaymentDialog: false // 是否显示支付状态对话框
        }
    },
    created() {
        this.getCommunity();
        this.getDepositOptions(1);
    },
    watch: {
        'form.leaseTerm': {
            handler(newVal) {
                if (newVal) {
                    this.getDepositOptions(newVal);
                }
            },
            immediate: true
        },
        'form.startDate'(newVal) {
            if (newVal && this.form.stopDate) {
                this.validateDateRange();
                this.calculateLeaseTerm();
            }
        },
        'form.stopDate'(newVal) {
            if (newVal && this.form.startDate) {
                this.validateDateRange();
                this.calculateLeaseTerm();
            }
        }
    },
    methods: {
        // 计算租期(月)
        calculateLeaseTerm() {
            if (!this.form.startDate || !this.form.stopDate) return;

            const start = new Date(this.form.startDate);
            const end = new Date(this.form.stopDate);

            // 计算月份差
            const months = (end.getFullYear() - start.getFullYear()) * 12;
            const monthDiff = months + (end.getMonth() - start.getMonth());

            // 确保至少一个月
            this.form.leaseTerm = Math.max(monthDiff, 1);

            // 更新租金方式
            if (this.form.leaseTerm > 0) {
                this.getDepositOptions(this.form.leaseTerm);
                this.calculateTotalAmount();
            }
        },
        // 获取小区
        getCommunity() {
            communityRequest.get('/community/selcomm')
                .then(res => {
                    this.communityOptions = res.data || [];
                })
                .catch(err => {
                    this.$message.error('获取小区列表失败');
                });
        },

        // 小区选择变化时获取对应广告位
        handleCommunityChange(communityId) {
            this.form.advertisingId = '';
            this.feeAmount = 0;
            this.advertisingOptions = [];

            if (communityId) {
                this.form.communityId = communityId;
                this.getAdvertising(communityId);
            }
        },

        // 获取小区对应的广告位
        getAdvertising(communityId) {
            request.get(`/advertising/idlist?commId=${communityId}`)
                .then(res => {
                    this.advertisingOptions = res.data || [];
                })
                .catch(err => {
                    this.$message.error('获取广告位列表失败');
                });
        },

        // 广告位选择变化时获取价格信息
        handleAdvertisingChange(advertisingId) {
            this.feeAmount = 0;
            if (advertisingId) {
                this.form.advertisingId = advertisingId;
                this.getAdvertisingInfo(advertisingId);
                this.calculateTotalAmount();
            }
        },

        // 根据广告位获取价格信息
        getAdvertisingInfo(advertisingId) {
            request.get(`/advertisingLease/getAdvertisingLeaseAdvertiserInfoById/${advertisingId}`)
                .then(res => {
                    if (res.data) {
                        this.feeAmount = res.data.advertisingPrice || 0;
                        this.brokerage = this.feeAmount;
                        this.form.advertisingPosition = res.data.advertisingPosition;
                        this.form.advertisingSize = res.data.advertisingSize;
                        this.form.collectionArea = res.data.advertisingSize;
                    }
                })
                .catch(err => {
                    this.$message.error('获取广告位信息失败');
                });
        },

        // 获取租金方式
        getDepositOptions(leaseTerm) {
            request.get(`/deposit/getLeaseDeposit/${leaseTerm}`)
                .then(res => {
                    this.depositOptions = res.data || [];
                })
                .catch(err => {
                    this.$message.error('获取租金方式失败');
                });
        },

        // 租金方式变化时处理
        handleRentWayChange(depositId) {
            this.form.depositId = depositId;
            if (this.form.advertisingId) {
                this.calculateTotalAmount();
            }
        },

        // 计算总金额
        calculateTotalAmount() {

            this.TotalAmount = this.feeAmount * this.form.leaseTerm;
            console.log(this.TotalAmount);
            console.log(this.leaseTerm);


            console.log(this.TotalAmount + '总金额');

        },

        // 验证日期范围
        validateDateRange() {
            const startDate = new Date(this.form.startDate);
            const stopDate = new Date(this.form.stopDate);

            // 验证结束日期不能早于开始日期
            if (stopDate < startDate) {
                this.$message.warning('结束日期不能早于起租日期');
                this.form.stopDate = '';
                return;
            }

            // 验证结束日期必须与开始日期同一天
            if (stopDate.getDate() !== startDate.getDate()) {
                this.$message.warning('结束日期必须与开始日期同一天');
                this.form.stopDate = '';
                return;
            }

            // 验证时间间隔至少一个月
            const months = (stopDate.getFullYear() - startDate.getFullYear()) * 12;
            const monthDiff = months + (stopDate.getMonth() - startDate.getMonth());

            if (monthDiff < 1) {
                this.$message.warning('租赁期限至少一个月');
                this.form.stopDate = '';
            }
        },

        // 格式化日期
        formatDate(date) {
            if (!date) return '';
            const d = new Date(date);
            return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
        },

        // 返回上一页
        goBack() {
            this.$router.go(-1);
        },
        async handleSave() {
            try {
                // 表单验证
                const valid = await this.$refs.contractForm.validate();
                if (!valid) {
                    this.$message.error('请完善表单信息');
                    return;
                }

                this.loading = true;

                // 构造提交数据
                const submitData = {
                    ...this.form,
                    signingDate: this.formatDate(this.form.signingDate),
                    startDate: this.formatDate(this.form.startDate),
                    stopDate: this.formatDate(this.form.stopDate),
                    advertisingPrice: this.feeAmount,
                    totalAmount: this.TotalAmount
                };

                // 提交表单到后端接口
                const res = await request.post('/advertisingLease/addAdvertisingLease', submitData);

                if (res.code === 200 && res.data) {
                    console.log(res.data);

                    const billId = res.data.billId;

                    const payWindow = window.open('', '_blank');

                    try {
                        // 获取支付页面HTML
                        const payRes = await request.post(`/billPay/payOrder`, { billId: billId });

                        // 写入新窗口
                        payWindow.document.write(payRes.data);
                        payWindow.document.close();

                        // 开始轮询支付状态
                        this.startPaymentPolling(billId);

                    } catch (err) {
                        payWindow.close();
                        this.$message.error('打开支付页面失败');
                        console.error(err);
                    }

                } else {
                    this.$message.error(res.message || '提交失败');
                }
            } catch (err) {
                this.$message.error('提交过程中发生错误');
                console.error(err);
            } finally {
                this.loading = false;
            }
        },

        // 开始支付状态轮询
        startPaymentPolling(billId) {
            this.showPaymentDialog = true;
            this.pollingCount = 0;
            this.maxPollingCount = 15; // 15次*4秒=60秒超时

            const timer = setInterval(async () => {
                if (this.pollingCount >= this.maxPollingCount) {
                    clearInterval(timer);
                    this.showPaymentDialog = false;
                    this.$message.warning('支付状态检查超时，请手动刷新页面查看支付结果');
                    return;
                }

                this.pollingCount++;

                try {
                    const res = await request.get(`/billPay/checkPaymentStatus/${billId}`);

                    if (res.data === true) {  // 支付成功
                        clearInterval(timer);
                        this.showPaymentDialog = false;
                        this.$message.success('支付成功');
                        this.$router.push({
                            path: '/payment/success',
                            query: { billId }
                        });
                    } else if (this.pollingCount === this.maxPollingCount) {
                        this.$message.warning('支付状态未确认，请稍后查看订单状态');
                    }
                } catch (err) {
                    console.error('检查支付状态失败', err);
                    clearInterval(timer);
                    this.showPaymentDialog = false;
                }
            }, 2000);  // 每2秒检查一次
        },

    }


}
</script>

<style scoped>
.contract-form {
    padding: 20px;
}

h3 {
    margin-bottom: 15px;
    font-size: 16px;
    font-weight: bold;
}

.basic-info,
.contract-info {
    margin-bottom: 20px;
}

.el-form-item {
    margin-bottom: 15px;
}

.button-group {
    margin-top: 20px;
}
</style>
